<template>
	<view class="upload">
		<uv-upload :fileList="fileList" multiple :width="width" :height="height" :maxCount="maxCount"
			:capture="['album', 'camera']" @afterRead="afterRead" @delete="deletePic">
			<view class="upload-btn u-flex-center"
				:style="{width:width + 'px',height:height + 'px',borderRadius:borderRadius + 'px'}">
				<uv-icon name="camera-fill" color="rgb(211, 212, 214)" v-if="!isUrl"></uv-icon>
				<image :src="url" class="image" v-else></image>
			</view>
		</uv-upload>
	</view>
</template>

<script setup>
	import { ref, computed, watch } from 'vue';
	import { UPLOAD_BASE_URL } from '@/utils/request.js'

	const props = defineProps({
		maxCount: {
			type: Number,
			default: 1
		},
		width: {
			type: Number,
			default: 40
		},
		height: {
			type: Number,
			default: 40
		},
		borderRadius: {
			type: [Number, String],
			default: 2
		},
		url: {
			type: String,
			default: ''
		},
		list: {
			type: Array,
			default: () => []
		}
	})

	const isUrl = computed(() => !!props.url);
	const token = uni.getStorageSync('token') || ''
	const fileList = ref([]);

	watch(
	  () => props.list,
	  (newList) => {
	    //props.list不是数组或为空
	    if (!Array.isArray(newList) || newList.length === 0) {
	      fileList.value = [];
	      return;
	    }
	    // 数组所有元素都是无效值（如["", null]）
	    const allInvalid = newList.every(url => {
	      return url === null || 
	             url === undefined || 
	             (typeof url === 'string' && url.trim() === '');
	    });
	    if (allInvalid) {
	      fileList.value = [];
	      return;
	    }
	    // 数组包含有效URL（过滤掉无效值后赋值）
	    const validUrls = newList
	      .filter(url => url !== null && url !== undefined && typeof url === 'string' && url.trim() !== '')
	      .map(url => ({ url }));
	      
	    fileList.value = validUrls;
	  },
	  { immediate: true }
	);

	// 删除图片
	const deletePic = (event) => {
		fileList.value.splice(event.index, 1);
		emit('uploadComple', fileList.value)
	}

	// 新增图片
	const afterRead = async (event) => {
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file)
		let fileListLen = fileList.value.length
		lists.map((item) => {
			fileList.value.push({
				...item,
				status: 'uploading',
				// message: '上传中'
			})
		})
		for (let i = 0; i < lists.length; i++) {
			const { data } = await uploadFilePromise(lists[i].url)
			let item = fileList.value[fileListLen]
			fileList.value.splice(fileListLen, 1, Object.assign(item, {
				status: 'success',
				message: '上传完成',
				url: data.file_url
			}))
			fileListLen++
		}
		emit('uploadComple', fileList.value)
	}

	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: UPLOAD_BASE_URL,
				filePath: url,
				name: 'file',
				header: {
					"Authorization": `Bearer ${token}`,
				},
				success: (res) => {
					resolve(JSON.parse(res.data))
				}
			});
		})
	}

	// 完成事件
	const emit = defineEmits(['uploadComple'])
</script>

<style lang="scss" scoped>
	.upload {

		.upload-btn {
			background-color: #f4f5f7;

			&:active {
				opacity: 0.5;
			}

			.image {
				width: 100%;
				height: 100%;
				display: block;
			}
		}
	}
</style>